#include "StdAfx.h"
#include "ListItem.h"

#include <vector>
#include <algorithm>

#include "Convert.h"
#include "guard.h"

static const wchar_t unicodeTag = 0xFEFF;

static void ReadFirstString(HANDLE hFile, std::wstring& buff, int size, bool& unicode)
{
    wchar_t unicodeTest = 0;
    DWORD nread;

    if (!::ReadFile(hFile, (LPVOID)&unicodeTest, sizeof(wchar_t), (LPDWORD)&nread, NULL))
        throw ListItemException();

    unicode = (unicodeTest == unicodeTag);

    if (unicode)
    {
        std::vector<wchar_t> readBuffer;
        readBuffer.assign(size, 0);

        if (!::ReadFile(hFile, (LPVOID)&readBuffer[0], readBuffer.size(), (LPDWORD)&nread, NULL))
            throw ListItemException();

        std::vector<wchar_t>::iterator res = find(readBuffer.begin(), readBuffer.end(), L'\r');
        buff.assign(readBuffer.begin(), res);

        return;
    }

    else
    {
        std::vector<char> readBuffer;
        std::vector<wchar_t> convert;

        readBuffer.assign(size, 0);

        ::SetFilePointer(hFile, 0, NULL, FILE_BEGIN);

        if (!::ReadFile(hFile, (LPVOID)&readBuffer[0], readBuffer.size(), (LPDWORD)&nread, NULL))
            throw ListItemException();

        if (!Convert::a2w((LPCSTR)&readBuffer[0], readBuffer.size(), convert))
            throw ListItemException();

        std::vector<wchar_t>::iterator res = find(convert.begin(), convert.end(), L'\r');
        buff.assign(convert.begin(), res);

        return;
    }
}

void ListItem::Init(ListItem& item)
{
    HANDLE hFile = CreateFile(item.FileName.c_str(), GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
    if (hFile == INVALID_HANDLE_VALUE)
        throw ListItemException();

    Guard fileGuard = MakeGuardF(::CloseHandle, hFile);

    ReadFirstString(hFile, item.Title, 100, item.unicode);

    FILETIME laTime;
    if (!::GetFileTime(hFile, &item.CreateTime, &laTime, &item.LastWriteTime))
        throw ListItemException();
}